from PyQt4 import QtGui,QtCore,uic
import Machine, Tool
import sys

from MachineSettingsWidget import MachineSettingsWidget
from AxisSettingsWidget import LinearAxisSettingsWidget,RotaryAxisSettingsWidget

class MachineSetupDialog(QtGui.QDialog):
    def __init__(self):
        QtGui.QDialog.__init__(self)

        uic.loadUi("ui/ui_files/MachineSetup.ui",  self)

        root = self.treeWidget.topLevelItem(0)
        if root != None: root.setExpanded(True)

        self.buttonBox.accepted.connect(self.acceptClicked)

        self.treeWidget.itemClicked.connect(self.itemClicked)
        self.treeWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.treeWidget.customContextMenuRequested.connect(self.showPopupMenu)

        self.machine = Machine.getCurrentMachine()

        self.updateAxisItems()
        self.updateToolItems()
# Signals
    def acceptClicked(self):
        widget = self.scrollArea.takeWidget()
        if widget != None: del widget
        print "Config accepted"
        self.accept()

    def itemClicked(self, item, column):
        widget = self.scrollArea.takeWidget()

        if widget != None: del widget

        if item.text(0) == "Settings":
            self.scrollArea.setWidget(MachineSettingsWidget())

        if item.parent() == None: return

        if item.parent().text(0) == "Axis":
            print "Axis setting: " + item.text(0)
            if item.text(0) == 'r':
                self.scrollArea.setWidget(RotaryAxisSettingsWidget(str(item.text(0))))
            else:
                self.scrollArea.setWidget(LinearAxisSettingsWidget(str(item.text(0))))

    def showPopupMenu(self, point):
        item = self.treeWidget.itemAt(point)

        print "Popup"

        if item == None:
            return
        
        menu = QtGui.QMenu(self)
        action = QtGui.QAction(self)

        if item.text(0) == "Tool Table":
            menu.addAction(item.text(0))
            menu.addSeparator()
            if self.machine.getType() == Machine.MachineType.Lathe:
                action.setText("Add Lathe Tool")
            else:
                action.setText("Add Milling Tool")
            action.setData(QtCore.QVariant(item))
            action.triggered.connect(self.addTool)

        elif item.parent().text(0) == "Tool Table":
            menu.addAction(item.text(0))
            menu.addSeparator()
            action.setText("Remove Tool")
            action.setData(QtCore.QVariant(item))
            action.triggered.connect(self.removeTool)

        menu.addAction(action)
        menu.popup(self.treeWidget.mapToGlobal(point))

# Functions
    def addTool(self):
        tool = None
        if self.machine.getType() == Machine.MachineType.Lathe:
            tool = Tool.LatheTool()
        else:
            tool = Tool.MillingTool()

        self.machine.addTool(tool)

        self.updateToolItems()

    def removeTool(self):
        item = self.sender().data().toPyObject()

        print item.text(0)

        tool = self.machine.getTool(str(item.text(0)))

        if tool != None:
            self.machine.removeTool(tool)

        self.updateToolItems()

    def updateAxisItems(self):
        items = self.treeWidget.findItems("Axis", QtCore.Qt.MatchRecursive)

        if len(items) == 0: return

        children = items[0].takeChildren()

        del children[:]

        for axis in Machine.getMachineTypeAxises(self.machine.getType()):
            item = QtGui.QTreeWidgetItem(0)
            item.setText(0, axis)
            items[0].addChild(item)

        items[0].setExpanded(True)

    def updateToolItems(self):
        items = self.treeWidget.findItems("Tool Table", QtCore.Qt.MatchRecursive)

        if len(items) == 0: return

        children = items[0].takeChildren()

        del children[:]

        for index, tool in self.machine.getTools().iteritems():
            item = QtGui.QTreeWidgetItem(0)
            item.setText(0, tool.getName())
            items[0].addChild(item)

        items[0].setExpanded(True)

def main():
    import os

    app = QtGui.QApplication(sys.argv)
    
    Machine.setCurrentMachine(Machine.loadMachineConfiguration(os.path.expanduser("~/.FreeCAM/FreeCAM")))
    Machine.getCurrentMachine().printToStream()

    setupDialog = MachineSetupDialog()
    setupDialog.show()

    ret = app.exec_()

    Machine.getCurrentMachine().printToStream()
#    Machine.saveMachineConfiguration(os.path.expanduser("~/.FreeCAM/FreeCAM"), machine)

    return sys.exit(ret)
    
